<?php
class Product_Service_OffshelfOnePiece
{
	public static function getPrintOrders($orders_code,$category,$orderType,$customerID,$type='*',$page=1,$pageSize=0,$orderBy=''){
		$orderModel = new Order_Model_Order();
		$orders = $orderModel->getByCategoryAndOrderType($orders_code,$category,$orderType,$customerID,$type,$page,$pageSize,$orderBy);
		return $orders;
	}
	
	public static function getPrintOrdersNew($condisiton,$type='*',$page=1,$pageSize=0,$orderBy=''){
		$orderModel = new Order_Model_Order();
		$orders = $orderModel->getByCategoryAndOrderTypeNew($condisiton,$type,$page,$pageSize,$orderBy);
		return $orders;
	}
		
	public static function printOrders($orderCodes,$members){
	
		$result = array();
		$category = "";
		
		//单号
		$opCode = self::generateCode();
		//先创建下架单 避免产生重复下架单
		$session = new Zend_Session_Namespace('userAuth');
		$user_id=$session->userID;     //操作人
		$pickRow = array(
				"op_code" => $opCode,
				"op_creater_id" => $user_id,
				"op_order_cnt" => 0,
				"op_product_cnt" => 0,
				"op_status" => 0,//配货单状态 未完成
				"op_create_date" => date("Y-m-d H:i:s"),
		);
		$opModel = new Product_Model_OrderPickup();
		$op_id = $opModel->create($pickRow);
		
		$splitArgs = 7;	//一个订单n个产品，分多页，每页最多显示$splitArgs个产品 
		$batch_count = 0;
		$orderlist = array();
		$errlist = array();
		$productCnt = 0;
		foreach($orderCodes as $orderCode){
		    
		    $o = Order_Service_Order::getByfield('orders_code', $orderCode);
		    if(empty($o)||$o['orders_print_type']!=0){		        
		        $o['err'] = $o['orders_code'].'不是一票一件';//错误信息
		        $errlist[] = $o;
		        continue;
		    }
			$orderProcess = new Order_Service_OrderProccess($orderCode);
			$order = $orderProcess->printOrder($opCode,$orderCode);

			if(isset($order['err'])){
				$errlist[] = $order;
			}else{			
				foreach($order['product_bantch'] as $v_){						
					$order['ws_code']=$v_['ws_code'];//取得第一个产品的货架
					break;
				}
				
				$batch_count += count($order['product_bantch']);
				$orderlist[$order['ws_code'].$order['orders_code']] = $order;
				
				// 				$result["orders"][$order['ws_code']."__".$order['order_id']] = $order;
// 				$category == ""?$category = $order["order_product"][0]['category']:"";
				$productCnt += $order['productCnt'];
			}
			
			
		}
		
		ksort($orderlist);//货架排序
		
		if($members){
			shuffle($members);//打乱数组
		}
		$arr = array();
		if(count($orderlist)>0){	
// 		    print_r($orderlist);	    
		    foreach($orderlist as $v){
		        if(isset($arr[$v['ws_code']])){
		            $arr[$v['ws_code']]['quantity']++;
		            $arr[$v['ws_code']]['orders_code'][] = $v['orders_code'];
		        }else{
                    $categoryName = isset($order["order_product"][0]['category']) ? $order["order_product"][0]['category']['poc_value'] : "";
                    $arr[$v['ws_code']] = array(
                            'ws_code' => $v['ws_code'],
                            'customer_id' => $v['customer_id'],
                            'product_id' => $v['order_product'][0]['product_id'],
                            'product_sku' => $v['customer_id'].$v['order_product'][0]['product_sku'],
                            'product_title' => $v['order_product'][0]['product_title'],
                            'category' => $categoryName,
                            'quantity' => 1,                            
                    )
                    ;
                    $arr[$v['ws_code']]['orders_code'][] = $v['orders_code'];
                }
		    }	
// 		   print_r($arr);    
           $spliceSize = count($arr)%count($members)==0?count($arr)/count($members):(count($arr)/count($members)+1);
		   $arr_chunk = array_chunk($arr,$spliceSize);//拆分数组
		   $arr_chunk_clone = array();
		   $pages = 0;
		   foreach($arr_chunk as $k=>$v){
                if ($k == 0) {
                    $productCnt = 0;
                    foreach($v as $v0){
                        $productCnt+=$v0['quantity'];
                    }
                    // 更新下架单
                    $pickRow = array(
                            "op_order_cnt" => $productCnt,
                            "op_product_cnt" => $productCnt,
                            "op_status" => 0, // 配货单状态 未完成
                            "op_create_date" => date("Y-m-d H:i:s")
                    );
                    $opModel = new Product_Model_OrderPickup();
                    $opModel->update($pickRow, $op_id);
                } else {
                    $opCode = self::generateCode();                 
                    $productCnt = 0;
                    $obj=new Order_Model_OrderPickupMap();
                    foreach($v as $v0){
                        $productCnt+=$v0['quantity'];
                        foreach($v0['orders_code'] as $code){//更新配货订单与订单对照表
                            $row = array('op_code'=>$opCode);
                            $mapRow = Order_Service_OrderPickupMap::getByfield('orders_code', $code);                             
                            $obj->update($row, $mapRow[0]['opm_id']);
//                             print_r($mapRow);exit;
                        }
                    }   
                    $pickRow = array(
                            "op_code" => $opCode,
                            "op_creater_id" => $user_id,
                            "op_order_cnt" => $productCnt,
                            "op_product_cnt" => $productCnt,
                            "op_status" => 0, // 配货单状态 未完成
                            "op_create_date" => date("Y-m-d H:i:s")
                    );
                    
                    $opModel = new Product_Model_OrderPickup();
                    $opModel->create($pickRow);                   
                   
                }
                preg_match('/^([0-9]+)_([0-9a-zA-Z]+)$/', $members[$k], $m);
                $userId = $m[1];
                $userName = $m[2];
                foreach($v as $v0){
                    foreach($v0['orders_code'] as $code){
                        $row = array('pickup_user_id'=>$userId);
                        Order_Service_Order::updateByOrdersCode($row, $code);//配货人
                    }
                }
                $v_chunk = array_chunk($v,$splitArgs);
                $arr_chunk_clone[] = array(
                        'user_name' => $userName,
                        'op_code' => $opCode,
                        'v_chunk' => $v_chunk
                );
                $pages+=count($v_chunk);
            }
// 		   print_r($arr_chunk_clone);
// 		   exit;
		}

		$result["orders"]=$arr_chunk_clone;
		$result["pages"]=$pages;
		$result["err_orders"]=$errlist;
		$result["orders_count"]=count($orderlist);
		$result['date'] = date("Y-m-d");
		$result['admin'] = $session->name;
			
		if(count($orderlist)==0){			
			//无成功订单，删除下架单
			$opModel = new Product_Model_OrderPickup();
			$opModel->delete($op_id);
		}
			

		return $result;
	}
	
	public function my_compare($a, $b) {
		if ($a[1] < $b[1])
			return -1;
		else if ($a[1] == $b[1])
			return 0;
		else
			return 1;
	}
	

	
	//生成下架单号
	public static function generateCode(){
		$sequence = "001";
		$offShelfModel = new Product_Model_OrderPickup();
		$offShelfs = $offShelfModel->getMaxByCurrentDate()->toArray();
		if(!empty($offShelfs)){
			$currentCode = current($offShelfs);
			$currentCode = substr($currentCode['op_code'],-3);
			$sequence = str_pad($currentCode + 1,3,"0",STR_PAD_LEFT);
		}
		$code = "U".date("ymd").$sequence;
		return $code;
	}
}